/**
 * Created by xushengbin on 2017/12/17.
 */
//弹出错误提示的登录框
$.showErr = function (str, func) {
    // 调用show方法
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_DANGER,
        title: '出错啦',
        message: str,
        size: BootstrapDialog.SIZE_SMALL,//size为小，默认的对话框比较宽
        buttons: [{// 设置关闭按钮
            label: '关闭',
            action: function (dialogItself) {
                dialogItself.close();
            }
        }],
        // 对话框关闭时带入callback方法
        onhide: func
    });
};
//confirm确认选择框
$.showConfirm = function (str, funcok, funcclose) {
    BootstrapDialog.confirm({
        title: '确认',
        message: str,
        type: BootstrapDialog.TYPE_WARNING, // <-- Default value is
        // BootstrapDialog.TYPE_PRIMARY
        closable: true, // <-- Default value is false，点击对话框以外的页面内容可关闭
        draggable: true, // <-- Default value is false，可拖拽
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        btnOKClass: 'btn-warning', // <-- If you didn't specify it, dialog type
        size: BootstrapDialog.SIZE_SMALL,
        // 对话框关闭的时候执行方法
        onhide: funcclose,
        callback: function (result) {
            // 点击确定按钮时，result为true
            if (result) {
                // 执行方法
                funcok.call();
            }
        }
    });
};
//Success提示框
$.showSuccessTimeout = function (str, func, timeout) {
    timeout = (typeof timeout !== 'undefined') ? timeout : 5000;
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_SUCCESS,
        title: '操作成功',
        message: str,
        size: BootstrapDialog.SIZE_SMALL,
        buttons: [{
            label: '确定',
            action: function (dialogItself) {
                dialogItself.close();
            }
        }],
        // 指定时间内可自动关闭
        onshown: function (dialogRef) {
            setTimeout(function () {
                dialogRef.close();
            }, timeout);
        },
        onhide: func
    });
};
function validate_form($form) {
    var formId = $form.attr('id');
    remove_error($form);
    var result = true;
    console.log(formId);
    switch (formId) {
        case 'paramForm' :
            console.log('validate work modal form');
            $.each(['one', 'two', 'three', 'four', 'five'], function (i, element) {
                $('input[name^="' + element + '"]').each(function (index, input) {
                    var value = parseInt($(input).val());
                    console.log(value);
                    //时
                    if (index === 0 || index === 2) {
                        if (isNaN(value) || value > 24 || value < 0) {
                            console.log(index);
                            console.log(element);
                            trigger_error($form, $(input), '小时格式错误，必须是0-24之间的数字');
                            result = false;
                            return false;
                        }
                    } else {
                        if (isNaN(value) || value > 60 || value < 0) {
                            console.log(index);
                            console.log(element);
                            trigger_error($form, $(input), '分钟格式错误，必须是0-60之间的数字');
                            result = false;
                            return false;
                        }
                    }
                })
            });
            break;
        case 'adForm':
            $form.find('input').each(function (index, input) {
                var value = parseInt($(input).val());
                if (isNaN(value) || value > 100 || value < 0) {
                    trigger_error($form, $(input), '必须1-100之间的数字');
                    result = false;
                    return false;
                }
            })
            break;
        case 'addForm':
            $form.find('input').each(function (index, input) {
                var value = $.trim($(input).val());
                if (value.length <= 0) {
                    trigger_error($form, $(input), '设备id、设备名称必填');
                    result = false;
                    return false;
                }
            })
            break;
    }
    if (result === true) {
        remove_error($form);
    }
    return result;
}
function trigger_error(form, target, msg) {
    target.addClass('has-error');
    if (msg) {
        form.find('.error-msg').show().text(msg);
    }
}
function remove_error(form) {
    form.find('input').removeClass('has-error');
    form.find('.error-msg').hide().text('');
}

$(function () {
    //手动模式
    if (typeof deviceInfo !== 'undefined' && deviceInfo.workData.model === '2') {
        $('.device-info .work').show();
    }
    $('#paramModal input').each(function () {
        console.log($(this).attr('name'));
        laydate.render({
            elem: this,
            type: 'time',
            format: 'H点m分'
        });
    });
    //时间选择器
    $('#paramModal').on('show.bs.modal', function () {
        $.each(['one', 'two', 'three', 'four', 'five'], function (i, element) {
            $('input[name^="' + element + '"]').each(function (index, value) {
                $(this).val(deviceInfo.duration[i][index]);
            })
        })
    });
    $('#paramForm').on('submit', function () {
        var validate = true;
        $(this).find('input').each(function (index, value) {
            console.log($(this).val());
            if ($.trim($(this).val()).length <= 0) {
                console.log($(this).attr('name'));
                alert('所有项都必填');
                validate = false;
                return false;
            }
        });
        return validate;
    })
    $('#clockModal').on('show.bs.modal', function () {
        laydate.render({
            elem: '#currentDate',
            type: 'datetime',
            value: new Date()
        });
    });
    $('.submit-modal').click(function (e) {
        var $form = $(this).closest('form');
        var validate = validate_form($form);
        if (validate === false) {
            return false;
        }
        var $modal = $(this).closest('.modal');
        var form = $form[0];
        console.log(form);
        var url = $form.attr('action');
        console.log(url);
        var method = $form.attr('method');
        $.ajax({
            url: url,
            type: method,
            dataType: 'json',
            // async: false,
            data: $form.serialize(),
            success: function (data) {
                $modal.modal('hide');
                if (data.status === 1) {
                    $.showSuccessTimeout(data.message, function () {
                        location.reload();
                    });
                } else {
                    $.showErr(data.message);
                }
            }
        })
    });


    $('<input type="button" class="pass-button-verifyCodeSend" value="获取短信验证码">').insertAfter($('#register-form-code'));
    $('<input type="button" class="pass-button-verifyCodeSend-forget" value="获取短信验证码">').insertAfter($('#forget-form-code'));
    //注册--获取验证码
    $('.pass-button-verifyCodeSend').on('click', function () {
        var $mobile = $('#register-form-mobile');
        var mobile = $mobile.val();
        if (!mobile.match(/^1[0-9]{10}$/)) {
            $mobile.closest('.form-group').addClass('has-error');
            $mobile.closest('.form-group').find('.help-block-error').text('手机号格式不正确');
            return false;
        }
        var that = $(this);
        $.post('/site/send-msg', {mobile: mobile, type: 1}, function (data) {
            data = JSON.parse(data);
            if (data.status === 1) {
                $.showSuccessTimeout('验证码已经发送到你的手机', function () {
                    var second = 60;
                    that.attr('disabled', true);
                    var interval = setInterval(settime, 1000);

                    function settime() {
                        that.val(second + ' s');
                        second--;
                        if (second === 0) {
                            that.val('获取短信验证码');
                            that.attr('disabled', false);
                            clearInterval(interval);
                        }
                    }
                }, 2000);
            } else {
                $.showErr(data.message);
            }
        })
    })
    //重置密码--获取验证码
    $('.pass-button-verifyCodeSend-forget').on('click', function () {
        var $mobile = $('#forget-form-mobile');
        var mobile = $mobile.val();
        if (!mobile.match(/^1[0-9]{10}$/)) {
            $mobile.closest('.form-group').addClass('has-error');
            $mobile.closest('.form-group').find('.help-block-error').text('手机号格式不正确');
            return false;
        }
        var that = $(this);
        $.post('/site/send-msg', {mobile: mobile, type: 2}, function (data) {
            data = JSON.parse(data);
            if (data.status === 1) {
                $.showSuccessTimeout('验证码已经发送到你的手机', function () {
                    var second = 60;
                    that.attr('disabled', true);
                    var interval = setInterval(settime, 1000);

                    function settime() {
                        that.val(second + ' s');
                        second--;
                        if (second === 0) {
                            that.val('获取短信验证码');
                            that.attr('disabled', false);
                            clearInterval(interval);
                        }
                    }
                }, 2000);
            } else {
                $.showErr(data.message);
            }
        })
    })
})